package com.wxlsoft.ui.conflist;

import java.awt.BorderLayout;
import java.io.File;
import java.io.FileFilter;
import java.util.Objects;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.tree.TreeSelectionModel;

import com.wxlsoft.config.ConfigImportHandler;
import com.wxlsoft.config.ConfigNodeContext;
import com.wxlsoft.config.model.ConfigFileType;
import com.wxlsoft.utils.LogUtils;

/**
 * 展示配置项目
 * @author wangxiaoliang
 */
public class ConfigTreeView extends JDialog {

    private static final long serialVersionUID = 1L;

    private File froot;
    
	public ConfigTreeView(String tableName, String froot) {
        this.froot = new File(froot);
        this.setTitle(tableName);
        this.setVisible(true);
        this.setBounds(100, 100, 800, 400);
        this.setLocationRelativeTo(null);
    }
    
    public void showtree(ConfigImportHandler importHandler) {
    	CheckNode root = findloop(froot);
    	ConfigNodeContext.setFileNode(root);
    	
        JTree tree = new JTree(root);
        tree.setCellRenderer(new CheckRenderer());
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        tree.putClientProperty("JTree.lineStyle", "Angled");
        tree.addMouseListener(new NodeSelectionListener(tree));
        
        JScrollPane sp = new JScrollPane(tree);
        ModePanel mp = new ModePanel(importHandler);
        JTextArea textArea = LogUtils.log;
        textArea.setText("");
        
        JScrollPane textPanel = new JScrollPane(textArea);
        JButton button = new JButton("确认发布");
        button.addActionListener(mp);
        
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(mp,     BorderLayout.CENTER);
        panel.add(button, BorderLayout.SOUTH);

        getContentPane().add(sp,    BorderLayout.CENTER);
        getContentPane().add(panel, BorderLayout.EAST);
        getContentPane().add(textPanel, BorderLayout.SOUTH);
    }
    
	private CheckNode findloop(File froot) {
		CheckNode rnode = new CheckNode(froot);
		File[] files = froot.listFiles((FileFilter) pathname -> pathname.isDirectory() || Objects.nonNull(ConfigFileType.parse(pathname.getName())));
		for (File file : files) {
			if (file.isDirectory()) {
				CheckNode cnode = findloop(file);
				rnode.add(cnode);
			} else {
				rnode.add(new CheckNode(file));
			}
		}
		return rnode;
	}

}